﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RonYee.Models;
using System.IO;
using RonYee.Service;

namespace RonYee.Controllers
{
    public class ImgNewsController : Controller
    {
        RongeDb db = new RongeDb();
        //
        // GET: /ImgNews/

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Index()
        {
            var img = from ig in db.ImgNewss select ig;
            return View(img.ToList());
        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Details(int id) 
        {
            ImgNews slider = db.ImgNewss.Find(id);
            if (slider == null)
            {
                return RedirectToAction("Index");
            }
            else 
            {
                string image=(from i in db.ImgNewss
                             where i.ImgNewsId==id
                             select i.ImgUrl).FirstOrDefault();
                string img1 = "..\\..\\" + image;
                ViewBag.img = img1;
                return View("Details", slider);
            }
        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Create()
        {
            return View();
        }

        [Authorize(Roles = "Admin,Editer")]
        [HttpPost]
        public ActionResult SliderCreate() 
        {
            string path = null;
            string fileOldName = "";
            string extension = "";
            foreach (string image in Request.Files) 
            {
                if (!RonYee.Service.HasFiles.HasFile(Request.Files[image])) 
                    continue;

                string createPath = AppDomain.CurrentDomain.BaseDirectory + @"Content\Sliders";
                path = HasFolders.HasFolder(createPath);

                //获得文件扩展名
                fileOldName = Path.GetFileName(Request.Files[image].FileName);
                extension = System.IO.Path.GetExtension(fileOldName);//扩展名 “.xxx”

                Stream fileStream = Request.Files[image].InputStream;
                string imageName=Path.GetFileName(Request.Files[image].FileName);

                //文件重命名
                string fileNewName = RandomNumberTo.RandomNumberToName() + extension;
                Request.Files[image].SaveAs(Path.Combine(path, fileNewName));
                
                string newsUrl = "";
                if (Request.Form["NewsUrl"] == null)
                {
                    newsUrl = "#";
                }
                else 
                {
                    newsUrl = Request.Form["NewsUrl"].ToString();
                }
                var slider = new RonYee.Models.ImgNews()
                {
                    ImgName=imageName,
                    ImgTitle=Request.Form["ImgTitle"],
                    Brief=Request.Form["Brief"],
                    ImgUrl = "Content\\Slider\\" + fileNewName,
                    DelUrl = Path.Combine(path, fileNewName),
                    NewsUrl= newsUrl,
                    Editor=HttpContext.User.Identity.Name.ToString(),
                    AddTime = DateTime.Now
                };
                db.ImgNewss.Add(slider);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View();
        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Edit(int id) 
        {
            ImgNews img = db.ImgNewss.Find(id);
            if (img == null)
            {
                return RedirectToAction("Index");
            }
            return View(img);
        }

        [Authorize(Roles = "Admin,Editer")]
        [HttpPost]
        public ActionResult Edit(ImgNews img) 
        {
            try
            {
                var imgnews = db.ImgNewss.Find(img.ImgNewsId);
                UpdateModel(imgnews);
                db.SaveChanges();
                return RedirectToAction("Details", new { id = img.ImgNewsId });
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", "修改失败，请查看详细错误信息:" + e);
            }
            return View(img);
        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Delete(int id)
        {
            ImgNews imgnews = db.ImgNewss.Find(id);
            if (imgnews == null)
                return RedirectToAction("Index");
            return View(imgnews);
        }

        [Authorize(Roles = "Admin,Editer")]
        [HttpPost]
        public RedirectToRouteResult Delete(int id, FormCollection collection)
        {
            var imgnews = db.ImgNewss.Find(id);

            //删除物理文件
            var delThis = (from d in db.ImgNewss
                             where d.ImgNewsId == id
                             select d).FirstOrDefault();

            System.IO.File.Delete(delThis.DelUrl);

            //删除数据库条目
            db.ImgNewss.Remove(imgnews);
            db.SaveChanges();
            return RedirectToAction("Index");
        }


    }
}
